package com.baohua.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.baohua.dao.InventoryDao;
import com.baohua.exception.BaohuaSystemException;
import com.baohua.model.Inventory;
import com.baohua.model.MaterielInformation;
import com.baohua.model.Staff;
import com.baohua.model.Supplier;
import com.baohua.service.InventoryService;
import com.baohua.util.BeanUtils;
import com.baohua.util.ExcelUtil;


@Service("inventoryService")
public class InventorySeviceImpl implements InventoryService {

	/**
	 * 查询库存数据
	 * @param inventory 库存对象
	 * @param pre_priceAmount 前置总额
	 * @param af_priceAmount 后置总额
	 * @param af_inventoryAmount 后置当前库存
	 * @param pre_inventoryAmount 前置当前库存
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public Map getInventoryList(Inventory inventory,String pre_priceAmount,
			   String af_priceAmount, String af_inventoryAmount, String pre_inventoryAmount, int page, int pagesize) {
		Map map = new HashMap();
		//拼接字符串
		StringBuffer sqlCount = new StringBuffer("select count(*) from Inventory s where 1=1");
		StringBuffer sql = new StringBuffer("from Inventory s where 1=1");
		if(!StringUtils.isEmpty(inventory.getInventoryNO())) {
			sql.append(" and s.inventoryNO = '" + inventory.getInventoryNO() + "'");
			sqlCount.append(" and s.inventoryNO = '" + inventory.getInventoryNO() + "'");
		}
		if(!StringUtils.isEmpty(inventory.getInventoryName())) {
			sql.append(" and s.inventoryName = '" + inventory.getInventoryName() + "'");
			sqlCount.append(" and s.inventoryName = '" + inventory.getInventoryName() + "'");
		}
		if(!StringUtils.isEmpty(pre_priceAmount)) {
			sql.append(" and s.priceAmount >= '" + pre_priceAmount + "'");
			sqlCount.append(" and s.priceAmount >= '" + pre_priceAmount + "'");
		}
		
		if(!StringUtils.isEmpty(af_priceAmount)) {
			sql.append(" and s.priceAmount <= '" + af_priceAmount + "'");
			sqlCount.append(" and s.priceAmount <= '" + af_priceAmount + "'");
		}
		
		if(!StringUtils.isEmpty(pre_inventoryAmount)) {
			sql.append(" and s.inventoryAmount >= '" + pre_inventoryAmount + "'");
			sqlCount.append(" and s.inventoryAmount >= '" + pre_inventoryAmount + "'");
		}
		
		if(!StringUtils.isEmpty(af_inventoryAmount)) {
			sql.append(" and s.inventoryAmount >= '" + af_inventoryAmount + "'");
			sqlCount.append(" and s.inventoryAmount >= '" + af_inventoryAmount + "'");
		}
		
		List<Inventory> list = inventoryDao.getInventory(sql.toString(),(page-1)*pagesize, pagesize);
		long count = inventoryDao.countInventory(sqlCount.toString());
		map.put("Rows", list);
		map.put("Total", count);
		
		return map;
	}
	
	/**
	 * 增加物料信息
	 * @param inventory
	 * @throws BaohuaSystemException
	 */
	@Override
	public void addRawMaterial(Inventory inventory) throws BaohuaSystemException {
		Inventory i = getInventoryByNO(inventory.getInventoryNO());
		if(i==null) {
			inventoryDao.addInventory(inventory);
		}else {
			throw new BaohuaSystemException("物料信息已经存在");
		}
		
	}
	
	/**
	 * 修改物料信息
	 * @param inventory
	 * @throws BaohuaSystemException
	 */
	@Override
	public void updateInventory(Inventory inventory) throws BaohuaSystemException {
			
		Inventory i = getInventoryByID(inventory.getInventoryID());
			if(i!=null) {
					if(i.getInventoryNO().equals(inventory.getInventoryNO())) {
						if(!BeanUtils.compareObject(i, inventory)) {
							BeanUtils.copyProperty(inventory, i);
							inventoryDao.updateInventory(i);
						}
				    }else {
				    	Inventory i1 = getInventoryByNO(inventory.getInventoryNO());
						if(i1==null) {
							BeanUtils.copyProperty(inventory, i);
							inventoryDao.updateInventory(i);
						}else {
							throw new BaohuaSystemException("物料编码已经存在");
						}
					}
					
				}else {
					throw new BaohuaSystemException("修改的物料信息不存在");
				}
	
		}
	
	/**
	 * 根据ID删除物料信息
	 * @param id
	 * @throws BaohuaSystemException
	 */
	public void delRawMaterial(int id) throws BaohuaSystemException {
		Inventory i = getInventoryByID(id);
		if(i!=null) {
			inventoryDao.deleteInventory(i);
		}else {
			throw new BaohuaSystemException("物料信息不存在");
		}
	}
	
	/**
	 * 根据物料编码进行查询库存
	 * @param InventoryNO
	 * @return
	 */
	@Override
	public Inventory getInventoryByNO(String InventoryNO) {
		Inventory i = inventoryDao.getInventoryByInventoryNo(InventoryNO);
		return i;
	}
	
	/**
	 * 根据ID查询物料信息
	 * @param InventoryID
	 * @return
	 */
	public Inventory getInventoryByID(int InventoryID) {
		Inventory i = inventoryDao.getInventoryByInventoryId(InventoryID);
		return i;
	}
	/**
	 * 根据物料编码的数组, 查询库存信息
	 * @param inventoryNOs
	 * @return
	 */
	public List<Inventory> queryByInventoryNOs(String[] inventoryNOs) {
		List<Inventory> list = new ArrayList<Inventory>();
		if(inventoryNOs.length!=0) {
		  list = inventoryDao.queryByInventoryNOs(inventoryNOs);
		}
		return list;
	}
	
	public void exportData(String fileName, List list, String sheetName,
			 HttpServletRequest request, HttpServletResponse response)
					 throws IllegalArgumentException, 
			 IOException, IllegalAccessException {
		InputStream bis = null;
		OutputStream bos = null;
		OutputStream output = null;
		ExcelUtil<Inventory> excelUtil = new ExcelUtil<Inventory>(Inventory.class);
		File file = new File(fileName);
		response.setContentType("application/x-msdownload;"); 
		output = new BufferedOutputStream(new FileOutputStream(file));
		if(list.size()==0) {
			excelUtil.exportExcel(list, sheetName, true, output);
		}else {
			excelUtil.exportExcel(list, sheetName, false, output);
		}
		 
		String agent = request.getHeader("USER-AGENT");
		if (null != agent && -1 != agent.indexOf("MSIE")){//IE
		// 设置文件头，文件名称或编码格式
		   response.setHeader("Content-Disposition", "attachment;filename="
		           + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
		}else{//firefox
			response.setHeader("Content-disposition", "attachment; filename="  
	                + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
		}
      response.setHeader("Content-Length", String.valueOf(file.length()));
		
			bis = new BufferedInputStream(new FileInputStream(file));  
          bos = new BufferedOutputStream(response.getOutputStream());  
          byte[] buff = new byte[2048];  
          int bytesRead;  
          while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
              bos.write(buff, 0, bytesRead); 
          }
          if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
	}
	
	
	private InventoryDao inventoryDao;

	public InventoryDao getInventoryDao() {
		return inventoryDao;
	}

	@Resource(name="inventoryDao")
	public void setInventoryDao(InventoryDao inventoryDao) {
		this.inventoryDao = inventoryDao;
	}

}
